/**
 * 工时表格组件
 */

'use client';

import React, { useState } from 'react';
import {
  Table,
  Tag,
  Avatar,
  Space,
  Button,
  Tooltip,
  Typography,
  Dropdown,
  Modal,
  message,
} from 'antd';
import {
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  MoreOutlined,
  ExportOutlined,
  UserOutlined,
} from '@ant-design/icons';
import type { ColumnsType, TableProps } from 'antd/es/table';
import dayjs from 'dayjs';
import type { Workload } from '../types/workload';

const { Text, Link } = Typography;

interface WorkloadTableProps extends Omit<TableProps<Workload>, 'columns' | 'dataSource'> {
  workloads: Workload[];
  loading?: boolean;
  total?: number;
  currentPage?: number;
  pageSize?: number;
  onView?: (workload: Workload) => void;
  onEdit?: (workload: Workload) => void;
  onDelete?: (workload: Workload) => void;
  onExport?: (workloads: Workload[]) => void;
  onPageChange?: (page: number, pageSize: number) => void;
}

export default function WorkloadTable({
  workloads,
  loading = false,
  total,
  currentPage = 1,
  pageSize = 30,
  onView,
  onEdit,
  onDelete,
  onExport,
  onPageChange,
  ...tableProps
}: WorkloadTableProps) {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const getPrincipalTypeTag = (type: string) => {
    const typeMap: Record<string, { color: string; text: string }> = {
      idea: { color: 'purple', text: '需求' },
      work_item: { color: 'blue', text: '工作项' },
      test_case: { color: 'green', text: '测试用例' },
    };
    const config = typeMap[type] || { color: 'default', text: type };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const getReviewStateTag = (state: string) => {
    const stateMap: Record<string, { color: string; text: string }> = {
      pending: { color: 'orange', text: '待审核' },
      approved: { color: 'green', text: '已通过' },
      rejected: { color: 'red', text: '已拒绝' },
    };
    const config = stateMap[state] || { color: 'default', text: state };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const handleDelete = (workload: Workload) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除这条工时记录吗？`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: () => {
        onDelete?.(workload);
      },
    });
  };

  const getActionMenu = (workload: Workload) => ({
    items: [
      {
        key: 'view',
        label: '查看详情',
        icon: <EyeOutlined />,
        onClick: () => onView?.(workload),
      },
      {
        key: 'edit',
        label: '编辑',
        icon: <EditOutlined />,
        onClick: () => onEdit?.(workload),
      },
      {
        type: 'divider' as const,
      },
      {
        key: 'delete',
        label: '删除',
        icon: <DeleteOutlined />,
        danger: true,
        onClick: () => handleDelete(workload),
      },
    ],
  });

  const columns: ColumnsType<Workload> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 120,
      fixed: 'left',
      render: (id: string, record) => (
        <Link onClick={() => onView?.(record)}>
          <Text code>{id.substring(0, 8)}...</Text>
        </Link>
      ),
    },
    {
      title: '工时主体类型',
      dataIndex: 'principal_type',
      key: 'principal_type',
      width: 120,
      filters: [
        { text: '需求', value: 'idea' },
        { text: '工作项', value: 'work_item' },
        { text: '测试用例', value: 'test_case' },
      ],
      onFilter: (value, record) => record.principal_type === value,
      render: (type: string) => getPrincipalTypeTag(type),
    },
    {
      title: '工时主体',
      key: 'principal',
      width: 250,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <Space size="small">
            <Tag color="blue">{record.principal.identifier}</Tag>
            <Text strong>{record.principal.title}</Text>
          </Space>
          <Text type="secondary" style={{ fontSize: 12 }}>
            类型: {record.principal.type}
          </Text>
        </Space>
      ),
    },
    {
      title: '工时类型',
      dataIndex: ['type', 'name'],
      key: 'workload_type',
      width: 100,
      render: (typeName: string) => (
        <Tag color="cyan">{typeName}</Tag>
      ),
    },
    {
      title: '工时时长',
      dataIndex: 'duration',
      key: 'duration',
      width: 100,
      align: 'center',
      sorter: (a, b) => a.duration - b.duration,
      render: (duration: number) => (
        <Text strong style={{ color: '#1890ff' }}>
          {duration}h
        </Text>
      ),
    },
    {
      title: '审核状态',
      dataIndex: 'review_state',
      key: 'review_state',
      width: 100,
      filters: [
        { text: '待审核', value: 'pending' },
        { text: '已通过', value: 'approved' },
        { text: '已拒绝', value: 'rejected' },
      ],
      onFilter: (value, record) => record.review_state === value,
      render: (state: string) => getReviewStateTag(state),
    },
    {
      title: '工时描述',
      dataIndex: 'description',
      key: 'description',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (description: string) => (
        description ? (
          <Tooltip title={description}>
            <Text>{description}</Text>
          </Tooltip>
        ) : (
          <Text type="secondary">-</Text>
        )
      ),
    },
    {
      title: '登记人',
      dataIndex: 'report_by',
      key: 'report_by',
      width: 120,
      render: (reportBy: Workload['report_by']) => (
        <Space size="small">
          <Avatar
            size="small"
            src={reportBy.avatar}
            icon={!reportBy.avatar ? <UserOutlined /> : undefined}
          >
            {!reportBy.avatar ? reportBy.display_name?.[0] : undefined}
          </Avatar>
          <Text>{reportBy.display_name}</Text>
        </Space>
      ),
    },
    {
      title: '登记日期',
      dataIndex: 'report_at',
      key: 'report_at',
      width: 120,
      sorter: (a, b) => a.report_at - b.report_at,
      render: (timestamp: number) => (
        <Tooltip title={dayjs.unix(timestamp).format('YYYY-MM-DD HH:mm:ss')}>
          {dayjs.unix(timestamp).format('YYYY-MM-DD')}
        </Tooltip>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 140,
      sorter: (a, b) => a.created_at - b.created_at,
      render: (timestamp: number) => (
        <Tooltip title={dayjs.unix(timestamp).format('YYYY-MM-DD HH:mm:ss')}>
          {dayjs.unix(timestamp).format('YYYY-MM-DD')}
        </Tooltip>
      ),
    },
    {
      title: '创建人',
      dataIndex: 'created_by',
      key: 'created_by',
      width: 120,
      render: (createdBy: Workload['created_by']) => (
        <Space size="small">
          <Avatar
            size="small"
            src={createdBy.avatar}
            icon={!createdBy.avatar ? <UserOutlined /> : undefined}
          >
            {!createdBy.avatar ? createdBy.display_name?.[0] : undefined}
          </Avatar>
          <Text>{createdBy.display_name}</Text>
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => onView?.(record)}
          />
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => onEdit?.(record)}
          />
          <Dropdown menu={getActionMenu(record)} trigger={['click']}>
            <Button
              type="link"
              size="small"
              icon={<MoreOutlined />}
            />
          </Dropdown>
        </Space>
      ),
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
    onSelect: (record: Workload, selected: boolean, selectedRows: Workload[]) => {
      console.log('选择变更:', record, selected, selectedRows);
    },
    onSelectAll: (selected: boolean, selectedRows: Workload[], changeRows: Workload[]) => {
      console.log('全选变更:', selected, selectedRows, changeRows);
    },
  };

  const handleExport = () => {
    const selectedItems = workloads.filter(item => selectedRowKeys.includes(item.id));
    const itemsToExport = selectedItems.length > 0 ? selectedItems : workloads;

    if (itemsToExport.length === 0) {
      message.warning('没有可导出的数据');
      return;
    }

    onExport?.(itemsToExport);
  };

  const tableTitle = () => {
    const totalHours = workloads.reduce((sum, workload) => sum + workload.duration, 0);
    
    return (
      <div className="flex justify-between items-center">
        <Space>
          <Text strong>工时列表</Text>
          <Text type="secondary">
            共 {workloads.length} 条记录
            {total && total !== workloads.length && ` (总计 ${total} 条)`}
            {selectedRowKeys.length > 0 && ` (已选择 ${selectedRowKeys.length} 项)`}
          </Text>
          {workloads.length > 0 && (
            <Text type="secondary">
              • 总工时: <Text strong style={{ color: '#1890ff' }}>{totalHours.toFixed(1)}</Text> 小时
            </Text>
          )}
        </Space>
        <Space>
          <Button
            icon={<ExportOutlined />}
            onClick={handleExport}
            disabled={workloads.length === 0}
          >
            导出 {selectedRowKeys.length > 0 ? `选中的 ${selectedRowKeys.length} 项` : `全部 ${workloads.length} 项`}
          </Button>
        </Space>
      </div>
    );
  };

  return (
    <Table
      {...tableProps}
      columns={columns}
      dataSource={workloads}
      rowKey="id"
      loading={loading}
      rowSelection={rowSelection}
      title={tableTitle}
      scroll={{ x: 1600, y: 600 }}
      pagination={
        // 如果没有分页参数或者数据量等于总数，则不显示分页
        !pageSize || !currentPage || workloads.length === (total || workloads.length) ? 
        false : 
        {
          total: total || workloads.length,
          pageSize: pageSize,
          current: currentPage,
          pageSizeOptions: ['10', '20', '30', '50', '100'],
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => {
            if (total === 0) {
              return '共 0 条';
            }
            return `第 ${range[0]}-${range[1]} 条，共 ${total} 条`;
          },
          onChange: onPageChange,
          onShowSizeChange: onPageChange,
          hideOnSinglePage: false,
          showLessItems: true,
        }
      }
      size="small"
      locale={{
        emptyText: workloads.length === 0 && !loading ?
          (
            <div className="py-8 text-center">
              <div className="text-gray-400 mb-2">
                暂无工时数据
              </div>
              <div className="text-sm text-gray-500">
                请在上方查询表单中调整筛选条件
              </div>
            </div>
          ) : undefined
      }}
    />
  );
}